import axios from "axios"
import Vue from "vue"
import querystring from "querystring"
import {errorAlert} from "../utils/alert"
import store from "../store"
import router from "../router"

//环境配置
if(process.env.NODE_ENV === "development"){
    Vue.prototype.$pre = "http://localhost:2000"
}
if(process.env.NODE_ENV === "production"){
    Vue.prototype.$pre = ""
}

//请求拦截
axios.interceptors.request.use(config => {
    if(config.url !== "/api/userLogin"){
    config.headers.authorization = store.getters.userInfo.token;
    }
    return config;
})

//响应拦截
axios.interceptors.response.use(res => {
    console.group("本次请求地址："+res.config.url)
    console.log(res);
    console.groupEnd()
    //错误处理
    if(res.data.code!==200){
        errorAlert(res.data.msg)
    }
    
    //掉线处理
    if (res.data.msg == '登录已过期或访问权限受限' ){
        store.dispatch("changeUserInfo",{})
        router.push("/login")
    }
    return res;
})

//封装get
export const get = (url,params = {}) => {
    return axios({
        url,
        method:"get",
        params
    })
}

//封装post
export const post = (url,params,haveFile = false) => {
    let data = null;
    if(haveFile){
        data = new FormData()
        for (let i in params){
            data.append(i,params[i])
        }
    }else{
        data = querystring.stringify(params)
    }
    return axios({
        url,
        method:"post",
        data
    })
}